<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


/* 关于返回结果的json格式建议如下：
data:执行成功返回的数据
status:简单的表示业务执行的状态，如成功success，登录失败，更新失败等
code:业务执行状态的代码（可不设计）
message:表示详细信息
version:版本号 
*/


class Taskset extends CI_Controller {

	var $_login_userid;
	
	function __construct()
	 {	  
		parent::__construct();
		//$this->_login_userid=0;
		$this->_login_userid=$this->get_login_userid();
		$this->load->database();
	 }
	 
//获得当前登录的用户id
	private function get_login_userid(){
		$this->load->library('tank_auth');
		$this->lang->load('tank_auth');
		if ($this->tank_auth->is_logged_in()){
			return $this->tank_auth->get_user_id();
		}else{
			return 0;
		}
	}
//检测当前登录用户是否是某个团队的成员
	private function check_is_member($teamid){
		$this->load->database();	
		$this->db->where('tid', $teamid);
		$query = $this->db->get('team_user');		
		if ($num_rows=$query->num_rows() > 0){
			return true;
		}else{
			return false;
		}
	}
//将数组转换成json，并输出
	private function array_to_json($array){
		$json_string = json_encode($array);    
		echo $json_string; 
	}

//按给定的sql查询并输出	
	private function query_to_json($sql){
		if($sql){
			
		}else{//防止出现空查询条件
			$sql="select 1 ";
		}
		$this->load->database();
		$query = $this->db->query($sql);
		if (($num_rows=$query->num_rows()) > 0){
			$result_array = array(
			   'data'=>$query->result_array(),
               'status'=> 'success',
			   'message'=>'查询到'.$num_rows."条记录"
			   );
		}else{
			$result_array = array(
               'status'=> 'nofound',
			   'message'=>'消息'.$this->db->last_query()
			   );
		}
		$this->array_to_json($result_array); 		
	}
	
//按给定的where子句生成查询task并输出
	private function query_by_where_to_json($where){
		$this->load->database();	
		if($where){
			
		}else{//防止出现空查询条件
			$where=" false ";
		}
//		echo $where;		
		$this->db->where('uid', $this->_login_userid);
		$this->db->where($where,NULL,FALSE);
		$this->db->order_by('sort','desc');
		$query = $this->db->get('task');
		if ($num_rows=$query->num_rows() > 0){
			$result_array = array(
			   'data'=>$query->result_array(),
               'status'=> 'success',
			   'message'=>'查询到'.$num_rows."条记录"
			   );
		}else{
			$result_array = array(
               'status'=> 'nofound',
			   'message'=>'消息'.$this->db->last_query()
			   );
		}
		$this->array_to_json($result_array); 		
	}

//取得任务（通用）
	public function gettask($where){
			if(isset($_POST['team'])){
				$this->get_team_task($_POST['team']);
				return;
			}else{
				$this->db->where('tid',NULL);
				$this->db->where('uid', $this->_login_userid);
				
				
			}
		$where='1';
		query_by_where_to_json($where);
	}


	
//取得当前用户的所有任务（不包括团队任务）
	public function getall($rand=0,$workarea=0){
	
		// $result_array = array();
		// $this->load->database();
		
		if($this->_login_userid){
			$this->db->where('tid',NULL);
			$this->db->where('uid', $this->_login_userid);
		}else{
			$this->db->where('uid', 5);
		}
		
		if($workarea||isset($_POST['workarea'])){
			$this->db->where('areaid', $workarea);
		}else{
		}

		
		
//		$this->db->where('stage !=', 'finish');//默认只取得所有未完成的任务
		$this->db->where('archive !=', '1');//默认只取得所有未归档的任务
		$this->db->order_by('sort desc,parent asc');
		
		$query = $this->db->get('task');
		if ($num_rows=$query->num_rows() > 0)
		{
//			$result_array['message']=$result_message;
			$result_array['data']=$query->result_array();
			$result_array['status'] = 'success';
		}else{
			$result_array['status'] = 'nofound';
		}
		$this->array_to_json($result_array);
	}
	
//取得某个团队的任务	
	public function get_team_task($teamid=0,$rand=0,$workarea=0){
		if(isset($_POST['team'])){
			$teamid=$_POST['team'];
		}
		$sql="select task.* from task,team,team_user where task.tid=team.id and team_user.tid=team.id AND team.id=".$teamid." AND team_user.uid=".($this->_login_userid?$this->_login_userid:'5')." order by in_date desc;";
		$this->query_to_json($sql);
	}	
	
	
	
//取得所有任务和所有团队任务，合并输出
	public function get_all_and_team($rand=0,$workarea=0){
		$result_array = array();
		$r1= array();
		$r2 =array();
		$this->load->database();
		if($this->_login_userid){
			$this->db->where('uid', $this->_login_userid);
		}else{
			$this->db->where('uid', 5);
		}
		if($workarea){
			$this->db->where('areaid', $workarea);
		}else{

		}
		
//		$this->db->where('stage !=', 'finish');//默认只取得所有未完成的任务
		$this->db->where('archive !=', '1');//默认只取得所有未归档的任务
		$this->db->order_by('sort desc,parent asc');
		$query1 = $this->db->get('task');
		if ($num_rows=$query1->num_rows() > 0)
		{
//			$result_array['message']=$result_message;
			$r1=$query1->result_array();
			$result_array['status'] = 'success';
		}else{
			$result_array['status'] = 'nofound';
		}
		$query2 = $this->db->query("select task.* from task,team,team_user where task.tid=team.id and team_user.tid=team.id AND team_user.uid=".($this->_login_userid?$this->_login_userid:'5')." order by in_date desc;");
		if ($num_rows=$query2->num_rows() > 0)
		{
			$r2=$query2->result_array();
		}	
		$result_array['data'] = array_merge($r1,$r2);
		$this->array_to_json($result_array);
	}

//----------------------------------------------------------------	
//取得某个任务集的子任务
	public function getSetTask($sid){
		$this->load->database();
        if($this->_login_userid){
			$this->db->where('uid', $this->_login_userid);
		}else{
			$this->db->where('uid', 5);
		}
		$this->db->where('sid', $sid);
//		$this->db->where('stage !=', 'finish');//默认只取得所有未完成的任务
		$this->db->order_by('sort desc');
		$query = $this->db->get('task_set');
		if ($num_rows=$query->num_rows() > 0)
		{
			$result_array['data']=$query->result_array();
			$result_array['status'] = 'success';
		}else{
			$result_array['status'] = 'nofound';
		}
			$this->array_to_json($result_array);		
	}
//-----------------------------------------------------------------	
	
//取得所有子孙节点的ID串（包含根节点本身，依靠MYSQL自定义函数）
	private function get_all_child_list($root){
		$this->load->database();
		$query = $this->db->query("select getTaskChildLst('".$root."') as childlist;");
		if ($query->num_rows() > 0)
		{
		   $row = $query->row(); 
		   return $row->childlist;
		} 
	}
	
//取得所有子孙任务列表（使用上述get_all_child_list函数）
	public function getallchild($parent=0,$workarea=0){
		$childlist=$this->get_all_child_list($parent);
	

		if($this->_login_userid){
			$this->db->where('uid', $this->_login_userid);
		}else{
			$this->db->where('uid', 5);
		}
		if($workarea){
			$this->db->where('areaid', $workarea);
		}else{

		}
		
//		$this->db->where('stage !=', 'finish');//默认只取得所有未完成的任务
		$this->db->where('archive !=', '1');//默认只取得所有未归档的任务
		$this->db->where(' FIND_IN_SET(id,"'.$childlist.'")>0 ',NULL,FALSE);//从子任务列表中取
		$this->db->order_by('sort desc,parent asc');
		$query = $this->db->get('task');
		if ($num_rows=$query->num_rows() > 0)
		{
			$result_array['data'] = $query->result_array();
			$result_array['status'] = 'success';
		}else{
			$result_array = array(
			   'status'=> 'nofound',
			   'message'=>'没有匹配的结果：'.$this->db->last_query()
		   );
        }
		$this->array_to_json($result_array);
	}
	
	
//取得所有任务的月份列表
	public function getmonthlist(){
//		echo 'rand:'.$rand;
//		echo 'workarea'.$workarea;
		$this->load->database();
        
//根据用户和团队进行条件选择        
		if($this->_login_userid){
            if(isset($_POST['team'])){
                if($this->check_is_member($_POST['team'])){
                    $this->db->where('tid',$_POST['team']);
                }else{
                    $this->db->where('tid',$_POST['team']);
                    $this->db->where('uid', $this->_login_userid);
                }
            }else{
                $this->db->where('uid', $this->_login_userid);
                $this->db->where('tid IS NULL ',NULL,FALSE);
            } 
		}else{
			$this->db->where('uid', 5);
		}
        
        $this->db->select('left(in_date,7) as month',false);
		$this->db->order_by('month','desc');
        $this->db->distinct();
		$query = $this->db->get('task');
        
//		$query = $this->db->query("select distinct left(in_date,7) as month  from  task where uid=".($this->_login_userid?$this->_login_userid:'5')." order by month desc;");
        if (($num_rows=$query->num_rows()) > 0){
			$result_array = array(
			   'data'=>$query->result_array(),
               'status'=> 'success',
			   'message'=>'查询到'.$num_rows."条记录,".$this->db->last_query()
			   );
		}else{
			$result_array = array(
               'status'=> 'nofound',
			   'message'=>'消息'.$this->db->last_query()
			   );
		}
        $this->array_to_json($result_array); 		
	}
	
//取得某月份的日期列表
	public function getdaylist($month){
		$this->load->database();
        
        //根据用户和团队进行条件选择        
		if($this->_login_userid){
            if(isset($_POST['team'])){
                if($this->check_is_member($_POST['team'])){
                    $this->db->where('tid',$_POST['team']);
                }else{
                    $this->db->where('tid',$_POST['team']);
                    $this->db->where('uid', $this->_login_userid);
                }
            }else{
                $this->db->where('uid', $this->_login_userid);
                $this->db->where('tid IS NULL ',NULL,FALSE);
            } 
		}else{
			$this->db->where('uid', 5);
		}
        
        $this->db->select('left(in_date,10) as day,count(*) as task_count',false);
        $this->db->where("DATE_FORMAT(in_date,'%Y-%m')='".$month."'",null,false);
        $this->db->group_by("day",false);
		$this->db->order_by('day','desc');
        $this->db->distinct();
		$query = $this->db->get('task');
        
/*		if($this->_login_userid){
			$this->db->where('uid', $this->_login_userid);
		}else{
			$this->db->where('uid', 5);
		}
		$query = $this->db->query("select distinct left(in_date,10) as day,count(*) as task_count  from  task where DATE_FORMAT(in_date,'%Y-%m')='".$month."' AND uid=".($this->_login_userid?$this->_login_userid:'5')." group by left(in_date,10) order by day desc;");
*/
        if (($num_rows=$query->num_rows()) > 0){
			$result_array = array(
			   'data'=>$query->result_array(),
               'status'=> 'success',
			   'message'=>'查询到'.$num_rows."条记录,".$this->db->last_query()
			   );
		}else{
			$result_array = array(
               'status'=> 'nofound',
			   'message'=>'消息'.$this->db->last_query()
			   );
		}
        $this->array_to_json($result_array);
	}	
	
//取得某月份的所有任务列表,如"2016-01"
	public function getmonthtask($year_month){
		$this->load->database();
        
        
        
		if($this->_login_userid){
			$this->db->where('uid', $this->_login_userid);
		}else{
			$this->db->where('uid', 5);
		}
		$this->db->where('DATE_FORMAT(in_date,"%Y-%m")', $year_month);
		$query = $this->db->get('task');
//		$query = $this->db->query("select distinct left(in_date,7) as month  from  task where uid=".($this->_login_userid?$this->_login_userid:'5')." order by month desc;");
		if ($num_rows=$query->num_rows() > 0)
		{
			$result_array['data']=$query->result_array();
			$this->array_to_json($result_array);
		}
	}
	
	public function getdaytask($year_month_day){
		$this->load->database();
        
        //根据用户和团队进行条件选择        
		if($this->_login_userid){
            if(isset($_POST['team'])){
                if($this->check_is_member($_POST['team'])){
                    $this->db->where('tid',$_POST['team']);
                }else{
                    $this->db->where('tid',$_POST['team']);
                    $this->db->where('uid', $this->_login_userid);
                }
            }else{
                $this->db->where('uid', $this->_login_userid);
                $this->db->where('tid IS NULL ',NULL,FALSE);
            } 
		}else{
			$this->db->where('uid', 5);
		}
        
        $this->db->where('DATE_FORMAT(in_date,"%Y-%m-%d")', $year_month_day);
		$this->db->order_by('in_date','desc');
		$query = $this->db->get('task');
        
        
 /*       
		if($this->_login_userid){
			$this->db->where('uid', $this->_login_userid);
		}else{
			$this->db->where('uid', 5);
		}
		$this->db->where('DATE_FORMAT(in_date,"%Y-%m-%d")', $year_month_day);
		$query = $this->db->get('task');
//		$query = $this->db->query("select distinct left(in_date,7) as month  from  task where uid=".($this->_login_userid?$this->_login_userid:'5')." order by month desc;");
*/
        if (($num_rows=$query->num_rows()) > 0){
			$result_array = array(
			   'data'=>$query->result_array(),
               'status'=> 'success',
			   'message'=>'查询到'.$num_rows."条记录,".$this->db->last_query()
			   );
		}else{
			$result_array = array(
               'status'=> 'nofound',
			   'message'=>'消息'.$this->db->last_query()
			   );
		}
        $this->array_to_json($result_array);
	}		

	public function index()
	{
		$this->load->helper('url');
		$this->load->view('welcome_message');
	}
	
	public function checklogin()
	{
		
		if($this->_login_userid==$_POST['uid']){
			$result_arr = array(
               'status'=> 1,
			   'message'=>'保持联系！',
			   'uid'=> $this->_login_userid
            );
		}else{
			$result_arr = array(
               'status'=> 0,
			   'message'=>'你未登录或已经过期了，请登录！',
			   'uid'=> $this->_login_userid
            );
		}
		$json_string = json_encode($result_arr);    
		echo $json_string;
	}


	public function insert(){
		
//			$newnode_sort=time();
//			$newnode_sort=(microtime(true)*1000)%100000000000;
			$newnode_sort= floor((microtime(true)-1400000000)*10);
//			$newnode_sort= (microtime(true)-1400000000)*10;
        
			$this->load->database();
        
//			$sql = "INSERT INTO task (title, parent,areaid,sort,in_date,uid) 
//			VALUES (".$this->db->escape($_REQUEST['title']).", ".$this->db->escape($_REQUEST['parent']).", ".$this->db->escape($_REQUEST['areaid']).",'".$newnode_sort."','".date("Y-m-d H:m:s")."','". $this->_login_userid."')";
//			$this->db->query($sql);
        
            $data = array(
                'tid'  => $_REQUEST['tid'],
                'sid' => $_REQUEST['sid'],
                'sort' => $newnode_sort,
			   'in_date' => date("Y-m-d H:m:s"),
			   'uid' => $this->_login_userid
            );
  			$this->db->insert('task_set', $data); 
        
			if($this->db->affected_rows()>0){
				$status=1;
                $newid=$this->db->insert_id();
			}else{
				$status=0;
			}
			$result_arr = array(
				   'status'=> $status,
				   'message'=>'消息'.$this->db->last_query(),
				   'data' => array(
						'newid'=>$newid,
						'newnode_sort'=>$newnode_sort
				   )
				);
				
			if($this->_login_userid==0){
				$result_arr['status'] = 0;
				$result_arr['message'] = '你未登录或已经过期了，新增的任务将不属于你私有，请先登录！';
			}		
			
		$json_string = json_encode($result_arr);    
		echo $json_string; 		
}
	
	public function change_parent(){
		if(!isset($_POST['taskid'])||!isset($_POST['new_parent'])){
			$result_arr['status']='fail';
			$result_arr['message']='参数非法';
			$json_string = json_encode($result_arr);    
			echo $json_string;
			return;
		}
		$this->load->database();

		//原只更新task的parent		
/* 		$data = array(
               'parent' => $_POST['new_parent']
            );
		$this->db->where('id',$_POST['taskid']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data); */
		//调用存储过程，完成更新task的parent和parents，以及所有子任务的parents
		$sql = "call changeTaskParentAndParents(".$_POST['taskid'].",".$_POST['new_parent'].",".$this->_login_userid.");";
		$this->db->query($sql);

		$result_arr= array();		
		if($this->db->affected_rows()>0){
			$result_arr['status']='success';
			$result_arr['message']='消息'.$this->db->last_query().'影响行数：'.$this->db->affected_rows();
		}else{
			$result_arr['status']='fail';
			$result_arr['message']='消息'.$this->db->last_query().'影响行数：'.$this->db->affected_rows();
		}
		$json_string = json_encode($result_arr);    
		echo $json_string;
	}
	
	public function edit(){
		$this->load->database();
		$data = array(
               'title' => $_POST['title']
            );
		$this->db->where('id',$_POST['id']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
//		echo   $_POST['taskid'],' TO ',$_POST['new_parent'];
//		echo $this->db->last_query();
//		echo $this->db->affected_rows();
	}
	
	public function editmore(){
		$this->load->database();
		$data = array(
               'comment' => $_POST['comment'],
			   'nodetype'=> $_POST['nodetype'],
			   'link'=> $_POST['link']
            );
		$this->db->where('id',$_POST['id']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
//		echo   $_POST['taskid'],' TO ',$_POST['new_parent'];
//		echo $this->db->last_query();
//		echo $this->db->affected_rows();
	}	
	public function change_stage(){
		$this->load->database();
		$data = array(
               'stage' => $_POST['stage']
            );
		$this->db->where('id',$_POST['id']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
//		echo   $_POST['taskid'],' TO ',$_POST['new_parent'];
//		echo $this->db->last_query();
//		echo $this->db->affected_rows();
	}
	
	
	public function change(){
		$this->load->database();
		$data = array(
               $_POST['parm1'] => $_POST['value1']
            );
		$this->db->where('id',$_POST['id']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
		if($this->db->affected_rows()>0){
			$status=1;
		}else{
			$status=0;
		}
		$result_arr = array(
               'status'=> $status,
			   'message'=>'消息'.$this->db->last_query()
			   );
			$json_string = json_encode($result_arr);    
			echo $json_string; 
	}
	
	public function archive(){
		// if(!$value){
			// $value=1;
		// }else{
			// $value=0;
		// }
		$this->load->database();
		$data = array(
               'archive' => $_POST['archive']
            );
		$this->db->where('id IN ('.$_POST['tasklist'].')');
//		$names = array($_POST['tasklist']);
//		echo $names;
//		$this->db->where_in('id', $names);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task', $data);
		if($this->db->affected_rows()>0){
			$status=1;
		}else{
			$status=0;
		}
		$result_arr = array(
               'status'=> $status,
			   'message'=>'消息'.$this->db->last_query()
			   );
			$json_string = json_encode($result_arr);    
			echo $json_string; 
	}
	
	
	public function changeSortInSet(){
		$this->load->database();
		$data = array(
               'sort' => $_POST['sort1']
            );
		$this->db->where('tid',$_POST['id1']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task_set', $data);
		$query1=$this->db->affected_rows();
		$message1="step1:".$query1.",".$this->db->last_query();
//		echo $message1;
//		echo $query1;
		
		$data = array(
               'sort' => $_POST['sort2']
            );
		$this->db->where('tid',$_POST['id2']);
		$this->db->where('uid', $this->_login_userid);
		$this->db->update('task_set', $data);
		$query2=$this->db->affected_rows();
		$message2="step2:".$query2.",".$this->db->last_query();
//		echo $message2;
//		echo $query2;
		
		if(($query1+$query2)>0){
			$status=1;
		}else{
			$status=0;
		}
		$result_arr = array(
               'status'=> $status,
			   'message'=>'消息'.$message1.$message2,
			   );
			$json_string = json_encode($result_arr);    
			echo $json_string; 
	}
	

	//该函数有用了
	public function del(){
		$taskid=$_POST['tid'];
		$setid=$_POST['sid'];
            $sql = "DELETE FROM task_set WHERE uid=".$this->_login_userid." AND tid=".$taskid." AND sid=".$setid." ;";
		$this->load->database();
			$this->db->query($sql);
            if($this->db->affected_rows()>0){
                $result_arr = array(
                   'status'=> 1,
                   'message'=>'已成功删除!'
			   );
            }else{
                $result_arr = array(
                   'status'=> 0,
                   'message'=>'出错了：'.$this->db->last_query()
			   );
            }

        $json_string = json_encode($result_arr);    
        echo $json_string; 
	}
	


	public function getnode($id,$sys=0){
		$this->load->database();	
		$this->db->where('id', $id); 
//		$this->db->where('uid', $this->_login_userid);
		$query1 = $this->db->get('task');
		

		if ($query1->num_rows() > 0)
		{
		    $row = $query1->row_array(); 
		    $query1->free_result(); 
//			print_r($row);
			if($row['nodetype']=='S'){
				$query = $this->db->get('task');
				$where='';
				if($row['tags']){					
					$tags=explode(' ', trim($row['tags']));  
					foreach ($tags as $tag){
						if($tag){
							$where.=' AND (tags LIKE "%'.$tag.'%" OR title LIKE "%'.$tag.'%") ';
						}
					}	
				}
				if($row['stage']){
					$where.=' AND stage="'.$row['stage'].'" ';
				}
				if($where){
					$where='1 AND id<>'.$row['id'].$where;
				}else{
					return; //防止出现空查询条件
				}
//				echo $where;
				
				$this->db->where($where,NULL,FALSE);
				$getway="S";
			}else{
				$this->db->where('parent', $id); //默认查询该ID的子节点
				$getway='P';//记录节点取得的方式
			}
		}
		if($sys==1){			
			$this->db->where('uid', 3);
		}else{
			$this->db->where('uid', $this->_login_userid);
		}
		
		$this->db->order_by('sort desc,in_date desc');
		$query2 = $this->db->get('task');
		if ($query2->num_rows() > 0)
		{
			$rows_arr=array();
			foreach ($query2->result_array() as $row)
			{
//				$rows_arr[$row['id']]=$row;
				$row['getway']=$getway;
				$rows_arr[]=$row;
			}
			$json_string = json_encode($rows_arr);    
			echo $json_string;
		} 		 
	}
	
	public function getnode_sys($id){
		$this->getnode($id,1);
	}
	
	private function get_by_where($where){
		$this->load->database();	
		if($where){
		}else{//防止出现空查询条件
			$row[id]="10";
			$row['title']="出错了，不能进行空查询！";
			$rows_arr[]=$row;
			$json_string = json_encode($rows_arr);    
			echo $json_string;
		}
//		echo $where;		
		$this->db->where('uid', $this->_login_userid);
		$this->db->where($where,NULL,FALSE);
		$getway="S";//记录节点取得的方式
		$this->db->order_by('sort','desc');
		$query = $this->db->get('task');
		if ($query->num_rows() > 0)
		{
			$rows_arr=array();
			foreach ($query->result_array() as $row)
			{
//				$rows_arr[$row['id']]=$row;
				$row['getway']=$getway;
				$rows_arr[]=$row;
			}
			$json_string = json_encode($rows_arr);    
			echo $json_string;
		} 		
	}
	
	public function search_by_post_parm(){
		$where=" 1 ";
		if($_REQUEST['active']){
			$where.=" AND active=".$this->db->escape($_REQUEST['active'])." ";
		}
		if($_REQUEST['parent']){
			$where.=" AND parent=".$this->db->escape($_REQUEST['parent'])." ";
		}
		if($_REQUEST['stage']===null){
		}else{
			$where.=" AND stage=".$this->db->escape($_REQUEST['stage'])." ";
		}
//		echo $where;
		$this->get_by_where($where);
		
	}
	
	public function search_by_stage($stage){
//		$where=" stage='".$stage."' ";
		$where=" active=1 AND stage='".$stage."' ";
		$this->get_by_where($where);
	}
	
	
	public function search_by_text(){
		$result_arr = array();
		$this->load->database();	
		$where='';
		$search_words=explode(' ', trim($_POST['search_words'])); 
		foreach ($search_words as $word){
			if($word){
				$where.=' AND (tags LIKE "%'.$word.'%" OR title LIKE "%'.$word.'%") ';
			}
		}
		if($where){
			$where='1'.$where;
		}else{
			$result_arr['status']='error';
			$result_arr['message']='不能执行一个空查询！';
			$json_string = json_encode($result_arr);    
			echo $json_string; 
			return;//防止出现空查询条件
		}
//根据是否在团队模式下还是普通登录用户模式下搜索，设置不同的条件
        if(isset($_POST['team'])){
            if($this->check_is_member($_POST['team'])){
                $this->db->where('tid',$_POST['team']);
            }else{
                $this->db->where('tid',$_POST['team']);
                $this->db->where('uid', $this->_login_userid);
            }
        }else{
            $this->db->where('uid', $this->_login_userid);
            $this->db->where('tid IS NULL ',NULL,FALSE);
        }
	
        
		$this->db->where($where,NULL,FALSE);
		$getway="S";//记录节点取得的方式
		$this->db->order_by('sort','desc');
		$query = $this->db->get('task');
		if (($num_rows=$query->num_rows()) > 0)
		{
			$rows_arr=array();
			foreach ($query->result_array() as $row)
			{
//				$rows_arr[$row['id']]=$row;
				$row['getway']=$getway;
				$rows_arr[]=$row;
			}
			$result_arr['data']=$rows_arr;
			$result_arr['status']='success';
			$result_arr['message']='共找到'.$num_rows.'个结果。';
		}else{
			$result_arr['status']='noresult';
			$result_arr['message']='没有匹配的结果！';		
		}
		$json_string = json_encode($result_arr);    
		echo $json_string; 
	}
	
	public function get($id){
		$this->load->database();
		$this->db->where('id', $id); 
		$query = $this->db->get('task');
		if ($query->num_rows() > 0)
		{
		    $row = $query->row_array(); 
			$json_string = json_encode($row);    
			echo $json_string;  
		} 
//		print_r($row);
	}
	private function get_parents_array($id){
		$this->load->database();
		$parents_array =array();
		$opt=$id;
		do{
			$this->db->where('id', $opt); 
			$query = $this->db->get('task');
//			echo $this->db->last_query();
			if ($query->num_rows() > 0)
			{
				$row = $query->row_array(); 
//				$result_message=var_export($row,true);
				$parents_array[] =$row['id'];
				$opt=$row['parent'];
				continue;
			}else{
				$opt=NULL;
				break;
			}
		}while($opt);
		return array_reverse($parents_array);
	}


	
	//取得最后更新的的任务
	public function getlastedit(){
		$this->load->database();
		if($this->_login_userid){
			$this->db->where('uid', $this->_login_userid);
		}else{
			$this->db->where('uid', 5);
		}
		$where = "lastupdate > DATE_SUB( NOW(),INTERVAL 1 MINUTE)";
		$this->db->where($where,NULL,FALSE);
//		$this->db->where('stage !=', 'finish');//默认只取得所有未完成的任务
//		$this->db->where('archive !=', '1');//默认只取得所有未归档的任务
		$this->db->order_by('parent asc,sort desc');
		$query = $this->db->get('task');
		if ($num_rows=$query->num_rows() > 0)
		{
//			$result_array['message']=$result_message;
			$result_array['data']=$query->result_array();
			$this->array_to_json($result_array);
		}
	}
	
//通过预生成的paents列表，取得所有祖先任务，并以json返回
	public function getparents_by_parentslist($id){
		$this->load->database();
		$sql="SELECT t1.*,find_in_set(t1.id,t2.parents) as p_order FROM task t1,task t2 WHERE t2.id=".$id." AND find_in_set(t1.id,t2.parents) order by p_order desc;";
		$query = $this->db->query($sql);
		if ($num_rows=$query->num_rows() > 0)
		{
			$result_array['data']=$query->result_array();
			$result_array['status'] = 'success';
		}else{
			$result_array['status'] = 'nofound';
		}
		//$result_array['data']=array_reverse($parents_array);
		$this->array_to_json($result_array);	
	}
	
	//通过不断循环查询，取得所有祖先任务
	public function getparents($id){
		$this->load->database();
		$parents_array =array();
		$opt=$id;
		do{
			$this->db->where('id', $opt); 
			$query = $this->db->get('task');
//			echo $this->db->last_query();
			if ($query->num_rows() > 0)
			{
				$row = $query->row_array(); 
				$result_message=var_export($row,true);
				$parents_array[] =$row;
				$opt=$row['parent'];
				continue;
			}else{
				$opt=NULL;
				break;
			}
		}while($opt);
		$result_array['message']=$result_message;
		$result_array['data']=array_reverse($parents_array);
		$json_string = json_encode($result_array);    
		echo $json_string; 		
	}
	
	//
	public function getparents_by_tag(){
		$all=array();
		$this->load->database();	
		$where='';
		$search_words=explode(' ', trim($_POST['search_words']));
// $search_words=explode(' ', trim('默认打开'));
		foreach ($search_words as $word){
			if($word){
				$where.=' AND (tags LIKE "%'.$word.'%") ';
			}
		}
		if($where){
			$where='1'.$where;
		}else{
			
			return;//防止出现空查询条件
		}
//		echo $where;		
		$this->db->where('uid', $this->_login_userid);
		$this->db->where($where,NULL,FALSE);
		$getway="S";//记录节点取得的方式

		$query = $this->db->get('task');
		if ($query->num_rows() > 0)
		{
			$rows_arr=array();
			$rows_arr=$query->result_array();
			foreach ($rows_arr as $row)
			{
				$all=array_merge($all,$this->get_parents_array($row['id']));
			}
			$all=array_unique($all);
			$json_string = json_encode($all);    
			echo $json_string;
		} 		 
	
	}
	
	//取得所有安排了日程的任务
	public function get_task_for_cal(){
//		$sql=('SELECT id, title, start_date AS start,allday FROM task WHERE start_date IS NOT NULL AND stage<>"finish" AND uid='.$this->_login_userid.';');
		$sql=('SELECT id, title, start_date AS start,allday FROM task WHERE start_date IS NOT NULL AND archive=0 AND uid='.$this->_login_userid.';');		
		$this->query_to_json($sql);
	}
	
	//取得所有安排了日程的任务（针对自定义的日历控件用）
	public function getmycal($theday=''){

//		$this->load->database();
//		$this->db->select('id, title, start_date AS start,allday');
//		$sql=('SELECT id, title, start_date AS start,allday FROM task WHERE start_date IS NOT NULL AND stage<>"finish" AND uid='.$this->_login_userid.';');

		$sql='SELECT id, title, start_date AS start,allday,stage FROM task WHERE start_date IS NOT NULL  ';
		if($this->_login_userid){
			if(isset($_POST['teamid'])){
				$sql.=' AND tid='.$_POST['teamid'];
			}else{
				$sql.=' AND uid='.$this->_login_userid.' AND tid IS NULL ';
			}
		}else{
			$sql.=' AND uid=5 AND tid IS NULL ';
		}
		if($theday){
			$sql.=' AND start_date BETWEEN date_sub("'.$theday.'",interval 7 day) AND  date_add("'.$theday.'",interval 42 day)';			
		}else{
			$sql.=' AND start_date BETWEEN date_sub(NOW(),interval 7 day) AND  date_add(NOW(),interval 42 day)';					
		}
		
		
		//如果设置了根任务参数，则只取根任务的下级任务，使用child_list自定义函数
		if(isset($_POST['root_task'])){
			$parent = $_POST['root_task'];
			$childlist=$this->get_all_child_list($parent);
			$sql.=' AND FIND_IN_SET(id,"'.$childlist.'")>0 ';//从子任务列表中取';
		}		
		$this->query_to_json($sql);

	}
	
}

